package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.YddUser;
import com.itheima.ydd.service.IYddUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_user")
@Slf4j
public class YddUserController {

    @Autowired
    private IYddUserService yddUserService;

    @GetMapping("/rowInfo")
    public ResultData findById(String id){
        YddUser yddUser=yddUserService.getById(id);
        return ResultData.ok("查询成功",yddUser);
    }

    @GetMapping("/list")
    public ResultData getList(String sex,String username,String mobile,Integer page,Integer limit){
        Page<YddUser> pageInfo=new Page<>(page,limit);
        LambdaQueryWrapper<YddUser> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(sex),YddUser::getSex,sex);
        queryWrapper.like(StringUtils.hasText(username),YddUser::getUsername,username);
        queryWrapper.like(StringUtils.hasText(mobile),YddUser::getMobile,mobile);
        yddUserService.page(pageInfo,queryWrapper);
        return ResultData.ok("", PageResult.init(pageInfo.getTotal(),pageInfo.getCurrent(),pageInfo.getSize(),pageInfo.getRecords()));
    }

    @PostMapping("/add")
    public ResultData add(@RequestBody YddUser yddUser){
        yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
        yddUserService.save(yddUser);
        return ResultData.ok("添加成功！",null);
    }

    @GetMapping("/del")
    public ResultData delete(String id){
        yddUserService.removeById(id);
        return ResultData.ok("删除成功！",null);
    }

    @PostMapping("/update")
    public ResultData update(@RequestBody YddUser yddUser){
        String password=yddUser.getPassword();
        if (password!=null){
            yddUser.setPassword(DigestUtils.md5DigestAsHex(yddUser.getPassword().getBytes()));
            yddUserService.updateById(yddUser);
        }else {
            yddUserService.updateById(yddUser);
        }
        return ResultData.ok("修改成功！",null);
    }
}
